<?php
/**
 * Created by PhpStorm.
 * User: 43074
 * Date: 2020/6/4
 * Time: 18:27
 */

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use app\Libraries;
use APP\Libs\WXBizMsgCrypt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Cache;

class WeChatController extends Controller
{
    public function __construct(\App\Libraries\Tool $jwt)
    {
        $this->Tool = $jwt;
    }

    public function verify_ticket(Request $request)
    {
        //配置
        $encodingAesKey = env('WeChat_EncodingAesKey');
        $token = env('WeChat_Token');
        $appId = env('WeChat_AppId');

        $data = $request->all();
        $timeStamp = $data['timestamp'];
        $nonce = $data['nonce'];
        $msg_sign = $data['msg_signature'];
        $encryptMsg = file_get_contents('php://input');

        $pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId);
        $xml_tree = new \DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;

        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);

        // 第三方收到公众号平台发送的消息
        $msg = '';
        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
        $date = $this->Tool->datas(1, '');
        if ($errCode == 0) {
            $xml = new \DOMDocument();
            $xml->loadXML($msg);
            $array_type = $xml->getElementsByTagName('InfoType');
            $InfoType = $array_type->item(0)->nodeValue;
            $array = array();
            $wechat_verifyticket_count = $this->Tool->index_count('wechat_programs');
            switch ($InfoType) {
                case 'component_verify_ticket': //请求ticket
                    $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
                    $component_verify_ticket = $array_e->item(0)->nodeValue;
                    $array['component_verify_ticket'] = $component_verify_ticket;
                    //保存
                    if ($wechat_verifyticket_count > 0) {
                        $wechat_verifyticket_first = $this->Tool->first('wechat_programs');
                        $array['updated_at'] = $date;
                        $array['component_verify_ticket_status'] = 2;
                        $this->Tool->mysql_where_edit('wechat_programs', 'id', $wechat_verifyticket_first->id, $array);
                    } else {
                        $array['created_at'] = $date;
                        $array['component_verify_ticket_status'] = 1;
                        $this->Tool->mysql_insert('wechat_programs', $array);
                    }
                    break;
                case 'unauthorized':   //取消授权
                    $array_appid = $xml->getElementsByTagName('AuthorizerAppid');
                    $authorizer_appid = $array_appid->item(0)->nodeValue;

                    break;
                case 'updateauthorized'://更新授权
                    $array_code = $xml->getElementsByTagName('AuthorizationCode');
                    $code = $array_code->item(0)->nodeValue;
                    //授权code

                    break;
                default:
                    echo "false";
                    die();
                    break;
            }
            return 'success';
        } else {
            $array['created_at'] = $date;
            $array['component_verify_ticket_status'] = 3;
            $array['component_verify_ticket'] = $errCode;
            $this->Tool->mysql_insert('wechat_programs', $array);
            return "false";
        }
    }

    public function receive_messages()
    {
        return Input::all();
    }

    /*
     * component_appid:第三方平台 appid
     * component_appsecret：第三方平台 appsecret
     * component_verify_ticket：微信后台推送的 ticket
     */
    public function component_access_token()
    {
        $wechat_verifyticket_first = $this->Tool->index_one_first('wechat_programs', 'component_access_token', '!=', null);
        if ($wechat_verifyticket_first->component_access_token_time < time()) {//过期后重新拉取
            $url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
            $data = '{
            "component_appid":"' . env('WeChat_AppId') . '" ,
            "component_appsecret": "' . env('WeChat_AppSecret') . '",
            "component_verify_ticket": "' . $wechat_verifyticket_first->component_verify_ticket . '"
        }';
            $ret = json_decode($this->Tool->https_post($url, $data));
            if (isset($ret->component_access_token)) {
                $array['component_access_token'] = $ret->component_access_token;
                $array['component_access_token_time'] = time() + 7200;//过期时间2小时
                $this->Tool->mysql_where_edit('wechat_programs', 'id', $wechat_verifyticket_first->id, $array);
                return $ret->component_access_token;
            } else {
                return $ret->errcode . '获取令牌异常';
            }
        } else {
            return $wechat_verifyticket_first->component_access_token;//使用原参数
        }
    }

    /*
     * component_access_token:令牌
     * component_appid:第三方平台 appid
     */
    public function pre_auth_code()
    {
        $wechat_verifyticket_first = $this->Tool->index_one_first('wechat_programs', 'pre_auth_code', '!=', null);
        if ($wechat_verifyticket_first->pre_auth_code_time < time()) {//过期后重新拉取
            $url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=" . $this->component_access_token();
            $data = '{"component_appid":"' . env('WeChat_AppId') . '"}';
            $ret = json_decode($this->Tool->https_post($url, $data));
            if (isset($ret->pre_auth_code)) {
                $array['pre_auth_code'] = $ret->pre_auth_code;
                $array['pre_auth_code_time'] = time() + 600;//过期时间10分钟
                $this->Tool->mysql_where_edit('wechat_programs', 'id', $wechat_verifyticket_first->id, $array);
                return $ret->pre_auth_code;
            } else {
                return $ret->errcode . '获取预授权码异常';
            }
        } else {
            return $wechat_verifyticket_first->pre_auth_code;//使用原参数
        }
    }

    /*
     * component_appid:第三方平台方 appid
     * pre_auth_code:预授权码
     * redirect_uri:回调 URI
     * auth_type:要授权的帐号类型:1 则商户扫码后，手机端仅展示公众号、2 表示仅展示小程序，3 表示公众号和小程序都展示
     */
    public function startAuth($auth_type = 3)
    {
        $redirect_uri = "http://jinyunapi.sqifu.com/api/startAuth_callback";
        $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid="
            . env('WeChat_AppId')
            . "&pre_auth_code=" . $this->pre_auth_code()
            . "&redirect_uri=" . $redirect_uri
            . "&auth_type=" . $auth_type;
        return view('indexs')->with(['name' => $url]);
//        return $this->Tool->content(20000,'',$url);
    }

    /*
     * component_access_token:令牌
     * component_appid:授权方 appid
     * authorization_code:授权码, 会在授权成功时返回
     */
    public function startAuth_callback()
    {
        if(Cache::has('appid')){
            $content['authorizer_appid']=Cache::get('appid');
            return $this->Tool->content(20000,'',$content);
        }
        $input = Input::only('auth_code', 'expires_in');
        $url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" . $this->component_access_token();
        $data = '{
            "component_appid":"' . env('WeChat_AppId') . '" ,
            "authorization_code": "' . $input['auth_code'] . '"
        }';
        $ret = json_decode($this->Tool->https_post($url, $data));
        if ($ret) {
            $date = $this->Tool->datas(1, '');
            $array['authorizer_appid'] = $ret->authorization_info->authorizer_appid;
            $array['authorization_code'] = $input['auth_code'];
            $array['authorizer_access_token'] = $ret->authorization_info->authorizer_access_token;
            $array['authorizer_access_token_time'] = time() + 7200;
            $array['authorizer_refresh_token'] = $ret->authorization_info->authorizer_refresh_token;
            $array['authorization_time'] = $date;
            $array['created_at'] = $date;
            $array['updated_at'] = $date;
            $applet_information = $this->Tool->index_one_first('applet_information', 'authorizer_appid', '=', $ret->authorization_info->authorizer_appid);
            if($applet_information){
                $this->Tool->mysql_where_edit('applet_information', 'authorizer_appid', $ret->authorization_info->authorizer_appid, $array);
            }else{
                $this->Tool->mysql_insert('applet_information', $array);
            }
            Cache::put('appid', $ret->authorization_info->authorizer_appid, 1);
        }
    }

    /*
     * component_access_token:令牌
     * component_appid:授权方 appid
     * authorizer_refresh_token:刷新令牌，获取授权信息时得到
     * authorizer_appid:授权方 appid
     */
    public function authorizer_refresh_token()
    {
        $authorizer_appid = 'wx0ece3a0f7fe29bc1';
        $applet_information = $this->Tool->index_one_first('applet_information', 'authorizer_appid', '=', $authorizer_appid);
        if ($applet_information->authorizer_access_token_time < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=" . $this->component_access_token();
            $data = '{
            "component_appid":"' . env('WeChat_AppId') . '" ,
            "authorizer_refresh_token":"' . $applet_information->authorizer_refresh_token . '" ,
            "authorizer_appid": "' . $authorizer_appid . '"
        }';
            $ret = json_decode($this->Tool->https_post($url, $data));
            $date['authorizer_access_token'] = $ret->authorizer_access_token;
            $date['authorizer_access_token_time'] = time() + 7200;
            $data = $this->Tool->datas(1, '');
            $date['authorization_time'] = $data;
            $date['updated_at'] = $data;
            $this->Tool->mysql_where_edit('applet_information', 'authorizer_appid', $authorizer_appid, $date);
            $access_token = $ret->authorizer_access_token;
        } else {
            $access_token = $applet_information->authorizer_access_token;
        }
        return $access_token;
    }

    /*
    * component_access_token:令牌
    * component_appid:授权方 appid
    * authorizer_appid:授权方 appid
    */
    public function authorizer_information()
    {
        $authorizer_appid = 'wx0ece3a0f7fe29bc1';
        $url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=" . $this->component_access_token();
        $data = '{
            "component_appid":"' . env('WeChat_AppId') . '" ,
            "authorizer_appid": "' . $authorizer_appid . '"
        }';
        $ret = $this->Tool->https_post($url, $data);
        return $ret;
    }
}